package com.ponhu.ea2.stockcenter.provider.schedule;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ponhu.ea2.stockcenter.provider.entity.StockWarehouse;
import com.ponhu.ea2.stockcenter.provider.service.biz.stockinit.GWallStockDataService;
import com.ponhu.ea2.stockcenter.provider.service.entity.StockWarehouseService;
import com.ponhu.ea2.wmscenter.model.bms.dto.PhWarehouseDto;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Wang
 * @date 2021/12/6 10:52 上午
 */
@Slf4j
@Component
public class StockWarehouseSyncTask {

    @Resource
    private GWallStockDataService gWallStockDataService;
    @Resource
    private StockWarehouseService stockWarehouseService;

    @XxlJob("stockWarehouseSyncTask")
    public void process() {
        List<PhWarehouseDto> allWarehouseList = gWallStockDataService.getAllWarehouseList();
        if (CollectionUtils.isEmpty(allWarehouseList)) {

            log.info("未获取到任何仓库数据，同步结束");
            return;
        }

        List<StockWarehouse> stockWarehouseList = stockWarehouseService.list();

        List<StockWarehouse> batchList = new ArrayList<>();
        for (PhWarehouseDto phWarehouseDto : allWarehouseList) {
            StockWarehouse warehouse = stockWarehouseList.stream().filter(
                    f -> f.getWarehouseCode().equals(phWarehouseDto.getWarehouseCode())).findFirst().orElse(null);

            if(warehouse == null){
                //添加
                StockWarehouse stockWarehouse = new StockWarehouse();
                BeanUtils.copyProperties(phWarehouseDto, stockWarehouse);
                stockWarehouse.setId(null);
                stockWarehouse.setCreateTime(null);
                stockWarehouse.setSaleStatus(phWarehouseDto.getSaleStatus() == 1);

                batchList.add(stockWarehouse);
            }else{
                //更新
                Integer id = warehouse.getId();
                BeanUtils.copyProperties(phWarehouseDto, warehouse);
                warehouse.setId(id);
                warehouse.setCreateTime(null);
                warehouse.setSaleStatus(phWarehouseDto.getSaleStatus() == 1);

                batchList.add(warehouse);
            }
        }

        stockWarehouseService.saveOrUpdateBatch(batchList);
        log.info("同步仓库信息成功");
    }
}
